//
//  AudioPlayerViewController.m
//  EDPS
//
//  Created by 张维扬 on 15/12/3.
//  Copyright © 2015年 张维扬. All rights reserved.
//

#import "AudioPlayerViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
#import "Masonry.h"
@interface AudioPlayerViewController ()
@property (nonatomic, retain) AVPlayer *player;
@property (nonatomic, retain) AVPlayerItem *playerItem;
@property (nonatomic, strong) UIView *backView;
@property (nonatomic, retain) UIView *topBackView;//上面的view用来返回和显示当前播放视频的名字
@property (nonatomic, retain) UIView *bottomBackView;//下面的view用来放置播放控件
@property (nonatomic, strong) UIButton *pauseImg;// 播放暂停图片
@property (nonatomic, strong) UIButton *playeImg;
@property (nonatomic, assign) BOOL isPlay;
@property (nonatomic, retain) UILabel *timeLabel;
@property (nonatomic, retain) UIButton *backBtn; //返回按钮
@property (nonatomic, retain) UIButton *playBtn; // 播放按钮
@property (nonatomic, retain) UISlider *slider; // 进度条
@property (nonatomic, retain) UIProgressView *progress;
@property (nonatomic, retain) UIView *lightView; // 调节亮度view
@property (nonatomic, retain) UIView *volumeView; // 调节声音view

@property(nonatomic, assign) CGFloat systemVolume;//系统音量
@property(nonatomic, strong) UISlider *volumeViewSlider; // 滑动音量
@property (nonatomic, strong) NSTimer *timer;
@end

@implementation AudioPlayerViewController
- (void)dealloc
{
    // dealloc  删除通知中心
    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:_player.currentItem];
}
// 屏幕支持方向
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskAll;
}
// 横屏播放
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    // 横屏方向
    return UIInterfaceOrientationLandscapeRight;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBarHidden = NO;
    self.isPlay = YES;
    //获取系统音量
    MPVolumeView *volumeView = [[MPVolumeView alloc] init];
    self.volumeViewSlider = nil;
    for (UIView *view in [volumeView subviews]){
        if ([view.class.description isEqualToString:@"MPVolumeSlider"]){
            self.volumeViewSlider = (UISlider *)view;
            break;
        }
    }
    // 创建播放器
    [self createPlayer];
    // AVPlayer播放完成通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.player.currentItem];
    // 添加观察者观察缓冲进度
    [self.playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
    
    [self initView];
    // 定时器
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(stack) userInfo:nil repeats:YES];
    
}
#pragma mark - 初始化一些View在上面放置控件
- (void)initView
{
    // 初始化背景view
    self.backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenHeight, ScreenWidth)];
    //    self.backView.backgroundColor = [UIColor cyanColor];
    [self.view addSubview:self.backView];
    
    // 创建点击一次和点击两次手势(播放和暂停)
    [self createGesture];
    
    // 创建上面的返回模态消失view
    self.topBackView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenHeight, ScreenWidth * 0.15)];
    self.topBackView.backgroundColor = [UIColor blackColor];
    [self.backView addSubview:self.topBackView];
    
    // 创建label
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(100, 15, ScreenWidth, 30)];
    title.text = self.model.title;
    title.textColor = [UIColor whiteColor];
    [self.topBackView addSubview:title];
    
    
    // 创建下面的控制视频播放的按钮的view
    self.bottomBackView = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenWidth - ScreenWidth * 0.15, ScreenHeight, ScreenWidth * 0.15)];
    self.bottomBackView.backgroundColor = [UIColor blackColor];
    [self.backView addSubview:self.bottomBackView];
    
    // 控制亮度View
    self.lightView = [[UIView alloc] initWithFrame:CGRectMake(0, 60, ScreenHeight / 2, ScreenWidth - 160)];
    //    self.lightView.backgroundColor = [UIColor orangeColor];
    self.lightView.alpha = 0.4;
    [self.view addSubview:self.lightView];
    
    // 创建声音view
    self.volumeView = [[UIView alloc] initWithFrame:CGRectMake(ScreenHeight / 2, 60, ScreenHeight / 2, ScreenWidth - 160)];
    //    self.volumeView.backgroundColor = [UIColor cyanColor];
    self.volumeView.alpha = 0.4;
    [self.view addSubview:self.volumeView];
    
    // 创建时间label
    [self createTimeLabel];
    
    // 按钮
    [self createButton];
    // 创建缓冲进度条
    [self createProgress];
    // 创建进度条
    [self createProgressSlider];
}
- (void)createPlayer
{
    // 网络视频
    NSURL *url = [NSURL URLWithString: self.model.url];
    NSLog(@"%@", url);
    self.playerItem = [[AVPlayerItem alloc] initWithURL:url];
    self.player = [[AVPlayer alloc] initWithPlayerItem:self.playerItem];
    
    AVPlayerLayer *layer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    layer.frame = CGRectMake(0, 0, ScreenHeight, ScreenWidth);
    [self.view.layer addSublayer:layer];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 播放视频
        [self.player play];
        
        [UIView animateWithDuration:5 animations:^{
            self.backView.alpha = 0;
            self.topBackView.alpha = 0;
            self.bottomBackView.alpha = 0;
        }];
        
    });
}

#pragma mark - 轻拍手势 + 滑动控制亮度声音手势
- (void)createGesture
{
    // 轻拍一次出现或者消失backview
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [self.view addGestureRecognizer:tap];
    
    // 轻拍两次暂停或者播放
    UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTapAction:)];
    [self.view addGestureRecognizer:doubleTap];
    doubleTap.numberOfTapsRequired = 2;
    // tap点击失败执行doubleTap方法
    [tap requireGestureRecognizerToFail:doubleTap];
    
    // 控制亮度手势
    UIPanGestureRecognizer *lightPan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(lightAction:)];
    [self.lightView addGestureRecognizer:lightPan];
    
    // 控制声音手势
    UIPanGestureRecognizer *volumePan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(volumeAction:)];
    [self.lightView addGestureRecognizer:volumePan];
    
}

#pragma mark - 轻拍一次方法
- (void)tapAction: (UITapGestureRecognizer *)tap
{
    if (self.backView.alpha == 1) {
        [UIView animateWithDuration:0.5 animations:^{
            self.backView.alpha = 0;
            self.topBackView.alpha = 0;
            self.bottomBackView.alpha = 0;
        }];
    }else if(self.backView.alpha == 0){
        [UIView animateWithDuration:0.5 animations:^{
            self.backView.alpha = 1;
            self.topBackView.alpha = 1;
            self.bottomBackView.alpha = 1;
        }];
    }
    if (self.backView.alpha == 1) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [UIView animateWithDuration:1 animations:^{
                self.backView.alpha = 0;
                self.topBackView.alpha = 0;
                self.bottomBackView.alpha = 0;
            }];
            
        });
    }
}
#pragma mark - 轻拍两次方法
- (void)doubleTapAction: (UITapGestureRecognizer *)doubleTap
{
    if (self.isPlay == YES) {
        [self.player pause];
        // 显示暂停图片
        self.pauseImg = [UIButton buttonWithType:UIButtonTypeCustom];
        self.pauseImg.frame = CGRectMake((ScreenWidth - 80) / 2, (ScreenHeight - 80) / 2, 80, 80);
        [self.pauseImg setBackgroundImage:[UIImage imageNamed:@"iconfont-bofangqizanting"] forState:UIControlStateNormal];
        [self.pauseImg addTarget:self action:@selector(playAction:) forControlEvents:UIControlEventTouchUpOutside];
        [UIView animateWithDuration:2 animations:^{
            [self.view addSubview:self.pauseImg];
        }];
        self.isPlay = NO;
    }else if(self.isPlay == NO){
        [self.player play];
        [UIView animateWithDuration:2 animations:^{
            [self.pauseImg removeFromSuperview];
        }];
        self.isPlay = YES;
    }
}
// 播放按钮方法
- (void)pauseImgAndPlayImgAction
{
    [self.player play];
}
#pragma mark - 控制亮度调节手势执行方法
- (void)lightAction: (UIPanGestureRecognizer *)lightPan
{
    // 获取屏幕位置
    CGPoint startPoint = [lightPan translationInView:self.lightView];
    NSLog(@"%.2f", startPoint.y);
    [UIScreen mainScreen].brightness = -startPoint.y * 0.005;
}
#pragma mark - 控制声音调节手势执行方法
- (void)volumeAction: (UIPanGestureRecognizer *)volumePan
{
    CGPoint startPoint = [volumePan translationInView:self.volumeView];
    NSLog(@"%.2f", startPoint.y);
    
    int index = (int)startPoint.y;
    if (index > 0) {
        
        if(index % 10 == 0){//每10个像素声音减一格
            if(_systemVolume >= 0.05){
                _systemVolume = _systemVolume-0.05;
                NSLog(@"systemVolume                    %.2f", _systemVolume);
                [_volumeViewSlider setValue:_systemVolume animated:YES];
                [_volumeViewSlider sendActionsForControlEvents:UIControlEventTouchUpInside];
            }
        }
        
    }else if(index < 0)
    {
        if(index % 10 == 0){//每10个像素声音增加一格
            //NSLog(@"+x ==%d",index);
            NSLog(@"11111111111111                      %.2f",_systemVolume);
            if(_systemVolume >= 0 && _systemVolume < 1){
                _systemVolume = _systemVolume+0.05;
                [_volumeViewSlider setValue:_systemVolume animated:YES];
                [_volumeViewSlider sendActionsForControlEvents:UIControlEventTouchUpInside];
            }
        }
    }
}
#pragma mark - 观察者缓冲进度条方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
        // 获取缓冲范围的数组
        NSArray *loadedTimeRanges = [[self.player currentItem] loadedTimeRanges];
        // 打印缓冲数组
        NSLog(@"loadedTimeRanges~~~~~~~~~~~~~~~~%@", loadedTimeRanges);
        // 取数组中的元素 转化成CMTimerange类型
        CMTimeRange timeRang = [loadedTimeRanges.lastObject CMTimeRangeValue];
        // 开始的点
        CGFloat start = CMTimeGetSeconds(timeRang.start);
        // 经历的时间
        CGFloat duration = CMTimeGetSeconds(timeRang.duration);
        // 获取已经缓冲的长度
        NSTimeInterval progressTime = start + duration;
        // 获取视频总长度
        CGFloat totalTime = self.playerItem.duration.value / self.playerItem.duration.timescale;
        // 给进度条赋值
        [self.progress setProgress:progressTime / totalTime animated:YES];
    }
}
#pragma mark - 创建缓冲进度条
- (void)createProgress
{
    self.progress = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, ScreenHeight, 0)];
    self.progress.tintColor = [UIColor orangeColor];
    self.progress.trackTintColor = [UIColor whiteColor];
    [self.bottomBackView addSubview:self.progress];
}
#pragma mark - 创建进度条
- (void)createProgressSlider
{
    self.slider = [[UISlider alloc]initWithFrame:CGRectMake(-10, -13, ScreenHeight, 30)];
    //注意这里要加UIControlStateHightlighted的状态，否则当拖动滑块时滑块将变成原生的控件
    [self.slider setThumbImage:[UIImage imageNamed:@"iconfont-huakuai"] forState:UIControlStateHighlighted];
    [self.slider setThumbImage:[UIImage imageNamed:@"iconfont-huakuai"] forState:UIControlStateNormal];
    //滑动之后的颜色
    self.slider.minimumTrackTintColor = [UIColor redColor];
    self.slider.maximumTrackTintColor = [UIColor clearColor];
    [self.bottomBackView addSubview:self.slider];
    [self.slider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];
}
- (void)sliderAction: (UISlider *)slider
{
    // 获取视频总时间
    CGFloat total = self.playerItem.duration.value / self.playerItem.duration.timescale;
    // 滑动之后当前的时间
    CGFloat current = total * slider.value;
    // 转换成CMtime时间系统才能知道
    CMTime time = CMTimeMake(current, 1);
    // 让视频暂停
    [self.player pause];
    // 滑动到什么时候让它播放
    [self.player seekToTime:time completionHandler:^(BOOL finished) {
        // 播放到滑动时间
        [self.player play];
    }];
}
#pragma mark - 创建时间显示label
- (void)createTimeLabel
{
    self.timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenHeight - 190, ScreenWidth - 40, 200, 30)];
    self.timeLabel.font = [UIFont systemFontOfSize:25];
    self.timeLabel.textColor = [UIColor whiteColor];
    [self.backView addSubview:self.timeLabel];
}
#pragma mark - 定时器方法
- (void)stack
{
    if (self.playerItem.duration.timescale != 0) {
        NSInteger totalMin = self.playerItem.duration.value / self.playerItem.duration.timescale / 60; // 视频总分钟
        NSInteger totalSec = self.playerItem.duration.value / self.playerItem.duration.timescale % 60; // 视频总秒
        
        NSInteger currentMin = (NSInteger)CMTimeGetSeconds([self.player currentTime]) / 60; // 当前播放分钟
        NSInteger currentSec = (NSInteger)CMTimeGetSeconds([self.player currentTime]) % 60; // 当前播放秒
        
        _slider.maximumValue = 1;//总共时长
        _slider.value = CMTimeGetSeconds([_playerItem currentTime]) / (_playerItem.duration.value / _playerItem.duration.timescale);//当前进度
        // 时间
        self.timeLabel.text = [NSString stringWithFormat:@"%02ld:%02ld / %02ld:%02ld", currentMin, currentSec, totalMin, totalSec];
    }
}
#pragma mark - 创建按钮方法
- (void)createButton
{
    // 返回按钮
    self.backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.backBtn setBackgroundImage:[UIImage imageNamed:@"iconfont-fanhui"] forState:UIControlStateNormal];
//    self.backBtn.backgroundColor = [UIColor redColor];
    self.backBtn.frame = CGRectMake(15, 10, 40, 40);
    [self.topBackView addSubview:self.backBtn];
    [self.backBtn addTarget:self action:@selector(backBtnAction) forControlEvents:UIControlEventTouchUpInside];
    // 播放按钮
    self.playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.playBtn setBackgroundImage:[UIImage imageNamed:@"iconfont-zhanting"] forState:UIControlStateNormal];
    self.playBtn.frame = CGRectMake(15, 15, 40, 40);
    [self.bottomBackView addSubview:self.playBtn];
    [self.playBtn addTarget:self action:@selector(playAction:) forControlEvents:UIControlEventTouchUpInside];
}
#pragma mark - 播放按钮方法
- (void)playAction: (UIButton *)btn
{
    btn.selected = !btn.selected;
    if (btn.selected) {
        [self.player pause];
        [self.playBtn setBackgroundImage:[UIImage imageNamed:@"iconfont-play"] forState:UIControlStateNormal];
    }else{
        [self.player play];
        [self.playBtn setBackgroundImage:[UIImage imageNamed:@"iconfont-zhanting"] forState:UIControlStateNormal];
    }
}
#pragma mark - 返回按钮方法
- (void)backBtnAction
{
    [self.player.currentItem cancelPendingSeeks];
    [self.player.currentItem.asset cancelLoading];
    self.player.rate = 0; // 播放器停止
    self.timer = nil;
    [self.timer invalidate];
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
// 播放结束时 接收通知  模态消失播放器页面
- (void)moviePlayDidEnd: (NSNotification *)Notification
{
    self.timer = nil;
    [self.timer invalidate];
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
